package com.tang.qzzp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tang.qzzp.entity.User;
import com.tang.qzzp.entity.UserHeader;
import com.tang.qzzp.service.UserHeaderService;
import com.tang.qzzp.service.UserService;
import com.tang.qzzp.utils.FileUtil;
import com.tang.qzzp.utils.ShiroUtil;
import com.tang.qzzp.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 唐海清
 * @Version V1.0
 * @Description ......
 */
@Controller
@RequestMapping("/user")
@Slf4j(topic = "userController")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private UserHeaderService userHeaderService;
    @Resource
    private FileUtil fileUtil;

    /**
     * 获取所有用户
     *
     * @return JSON
     * @Author thq
     */
    @PostMapping("/getUsers")
    @ResponseBody
    public String getUsers() {
        List<User> userList = userService.list();
        String json = JSONObject.toJSONString(userList);
        log.info("所有用户 : {}", json);
        return json;
    }

    /**
     * 返回个人首页
     *
     * @Author thq
     */
    @GetMapping("/toMyInfo")
    public String toMyInfo(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();
        String userName = currentUser.getUserName();
        log.info("返回个人首页 : {}", userName);
        model.addAttribute("userName", userName);
        model.addAttribute("currentUser", currentUser);
        return "user/myInfo";
    }

    /**
     * @param pageNumber 当前页数
     * @Author thq
     */
    @GetMapping("/getUserHeader")
    @ResponseBody
    public void getUserHeader(@RequestParam("pageNumber") Integer pageNumber,
                              HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");

        byte[] result;
        User currentUser = ShiroUtil.getCurrentUser();
        String userId = currentUser.getUserId();
        QueryWrapper<UserHeader> wrapper = new QueryWrapper<>();
        wrapper.eq("user_header_id", userId);
        UserHeader userHeader = userHeaderService.getOne(wrapper);
        result = userHeader.getUserHeaderPhoto();
        try {
            OutputStream outputStream = response.getOutputStream();
            InputStream in = new ByteArrayInputStream(result);
            int len;
            byte[] buf = new byte[0];
            try {
                buf = new byte[1024];
            } catch (Exception e) {
                e.printStackTrace();
            }
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            log.info("图片输出完毕");
        } catch (IOException e) {
            log.error("发生异常 : {}", e.getMessage());
        }
    }


    /**
     * 上传用户头像
     *
     * @param file 头像文件
     * @return boolean
     */
    @PostMapping("/uploadUserHeader")
    @ResponseBody
    @SuppressWarnings("all")
    public boolean uploadUserHeader(@RequestParam("file") MultipartFile file) {
        boolean result = false;
        if (!fileUtil.isEmpty(file)) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            log.info("当前用户 : {}", ShiroUtil.getUserName());
            log.info("上传文件名 : {}", fileUtil.getFileName(file));
            try {
                byte[] bytes = file.getBytes();

                UserHeader userHeader = new UserHeader();
                userHeader.setUserHeaderId(ShiroUtil.getCurrentUser().getUserId());
                userHeader.setUserHeaderPhoto(bytes);
                userHeader.setCreateTime(TimeUtil.getCurrentTime());
                userHeader.setUpdateTime(TimeUtil.getCurrentTime());
                userHeader.setVersion(1);
                userHeader.setDeleted(0);

                userHeaderService.save(userHeader);
                log.info("上传文件成功");
                result = true;
            } catch (IOException e) {
                log.info("发生了异常 : {}", e.getMessage());
            }
        }
        return result;
    }

    /**
     * 跳转用户修改信息界面
     *
     * @return html
     */
    @GetMapping("/toUpdateUserInfo")
    public String toUpdateUserInfo(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();
        String userName = currentUser.getUserName();
        log.info("用户前往修改个人信息页面 : {}", userName);
        model.addAttribute("userName", userName);
        model.addAttribute("currentUser", currentUser);
        return "user/updateUserInfo";
    }

    /**
     * 更改用户信息
     *
     * @param request request
     * @return boolean
     */
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public boolean updateUserInfo(HttpServletRequest request) {
        String userId = ShiroUtil.getUserId();
        User currentUser = userService.getById(userId);
        int version = currentUser.getVersion();
        version = version + 1;

        String json = request.getParameter("data");
        log.info("请求json : {}", json);

        JSONObject jsonObject = JSON.parseObject(json);
        String userName = (String) jsonObject.get("userName");
        String userPassword = (String) jsonObject.get("userPassword");
        String userEmail = (String) jsonObject.get("userEmail");

        currentUser.setUserEmail(userEmail);
        currentUser.setUserName(userName);
        currentUser.setUserPassword(userPassword);
        currentUser.setVersion(version);

        return userService.updateById(currentUser);
    }

    /**
     * 根据用户ID逻辑删除用户
     *
     * @param userId userID
     * @return Map
     */
    @PostMapping("/deleteUserInfo/{userId}")
    @ResponseBody
    public Map<String, Object> deleteUserInfo(@PathVariable("userId") String userId) {
        Map<String, Object> resultMap = new HashMap<>();
        //先判断用户该用户ID是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("user_is_deleted", 0);
        User user = userService.getOne(wrapper);
        log.info("user : {}", user);
        if (user != null) {
            user.setDeleted(1);
            userService.updateById(user);
            log.info("逻辑删除成功 : {}", userId);
            resultMap.put("result", "删除成功！");
        } else {
            log.info("逻辑删除失败 : {}", userId);
            resultMap.put("result", "删除失败！");
        }
        return resultMap;
    }

}